package controller

import (
	"bytes"
	"errors"
	"gitee.com/saxon134/go-utils/saData"
	"gitee.com/saxon134/go-utils/saData/saError"
	"gitee.com/saxon134/go-utils/saData/saTime"
	"gitee.com/saxon134/go-utils/saData/saUrl"
	"gitee.com/saxon134/workflow/api"
	"gitee.com/saxon134/workflow/db"
	"gitee.com/saxon134/workflow/errs"
	"github.com/gin-gonic/gin"
	"mime/multipart"
	"strings"
	"time"
)

func Upload(c *api.Context) (res *api.Response, err error) {
	gc, _ := c.Context.(*gin.Context)
	if gc == nil {
		err = errors.New("仅支持HTTP请求")
		return
	}

	file, _ := gc.FormFile("file")
	path := gc.PostForm("path")
	var fileSuffix string

	if file == nil {
		buf := new(bytes.Buffer)
		w := multipart.NewWriter(buf)
		var f_src multipart.File
		defer func() {
			_ = w.Close()
			if f_src != nil {
				_ = f_src.Close()
			}
		}()

		f_src, file, err = gc.Request.FormFile("file")

		if file != nil {
			fileSuffix = file.Filename
			lastDotIndex := 0
			for i := 0; i < len(fileSuffix); i++ {
				if saData.SubStr(fileSuffix, i, 1) == "." {
					lastDotIndex = i
				}
			}
			fileSuffix = saData.SubStr(fileSuffix, lastDotIndex, saData.StrLen(fileSuffix)-lastDotIndex)
		}

		if err != nil || f_src == nil {
			if gc.Request.MultipartForm != nil {
				for k, v := range gc.Request.MultipartForm.File {
					if k != "" && v != nil {
						headers := new(multipart.FileHeader)
						f_src, headers, err = gc.Request.FormFile(k)

						if headers != nil {
							fileSuffix = headers.Filename
							lastDotIndex := 0
							for i := 0; i < len(fileSuffix); i++ {
								if saData.SubStr(fileSuffix, i, 1) == "." {
									lastDotIndex = i
								}
							}
							fileSuffix = saData.SubStr(fileSuffix, lastDotIndex, saData.StrLen(fileSuffix)-lastDotIndex)
						}
						break
					}
				}
			}
		}

		if err != nil || f_src == nil {
			return nil, errs.New(err)
		}
	}
	if file == nil {
		return nil, errors.New("file is empty")
	}

	//文件类型
	var f_type = "files/"
	{
		//文件后缀
		if fileSuffix == "" {
			fileSuffix = file.Filename
			lastDotIndex := 0
			for i := 0; i < len(fileSuffix); i++ {
				if saData.SubStr(fileSuffix, i, 1) == "." {
					lastDotIndex = i
				}
			}
			fileSuffix = saData.SubStr(fileSuffix, lastDotIndex, saData.StrLen(fileSuffix)-lastDotIndex)
		}

		if fileSuffix != "" {
			f_type = fileType(fileSuffix)
		}
	}

	var now = time.Now()

	//完整文件存储路径，包含文件名
	if path == "" {
		path = "omc/" + f_type + now.Format(saTime.FormatYMDSimple) + "/"
	} else {
		if strings.HasSuffix(path, "/") == false {
			path += "/"
		}
		path = strings.TrimPrefix(path, "/")
	}
	path += saData.String(c.Account.Id) + "_" + saData.String(now.UnixMilli())
	path += fileSuffix

	//存储文件
	{
		//读取文件内容
		src, err := file.Open()
		if err != nil {
			return nil, saError.StackError(err)
		}
		defer func() {
			if src != nil {
				_ = src.Close()
			}
		}()

		err = db.Oss.Upload(path, src)
		if err != nil {
			return nil, errs.New(err)
		}
	}
	return &api.Response{Result: map[string]string{"name": path, "url": saUrl.AddUriRoot(path, saUrl.NullImgStyle)}}, nil
}

func fileType(suffix string) string {
	suffix = strings.ToLower(suffix)
	if strings.HasPrefix(suffix, ".") == false {
		suffix = "." + suffix
	}
	switch suffix {
	case ".mp4", ".mov", ".avi", ".flv", ".wmv", ".m4v", ".qt", ".asf", ".mpeg", ".mpg", ".vob":
		return "video/"
	case ".mp3", ".wav", ".aac", ".wma", ".rm", ".flac", ".midi", ".cda":
		return "voice/"
	case ".png", ".jpg", ".jpeg", ".bmp", ".gif", ".ico":
		return "images/"
	default:
		return "files/"
	}
}
